﻿//todo: by zjp1907
using Captura.Models;
using Captura.Video;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace Captura.ViewModels
{
    public class RecordTimesManager
    {

        const int DayToSeconds = 86400;

        public static bool Manage(Settings Settings)
        {
            var actives = Settings.RecordTimes.Where(x => x.IsActive).ToList();
            if (actives.Count() == 0)
            {
                Settings.PreStartCountdown = 0;
                Settings.Duration = 0;
                return false;
            }

            int preStartCountdown = 0;
            int _preStartCountdown = int.MaxValue;

            for (int i = 0; i < actives.Count; i++)
            {
                var rt = actives[i];
                //test
                //int h = 6;
                //int m = 25;
                //rt.StartTimeHour = h;
                //rt.StartTimeMinute = m + i;
                //rt.StartTimeSecond = 0;
                //rt.StopTimeHour = h;
                //rt.StopTimeMinute = m + i;
                //rt.StopTimeSecond = 10;
                //test
                var now = (int)DateTime.Now.TimeOfDay.TotalSeconds;
                var remained = DayToSeconds - now;
                var start = (int)new TimeSpan(rt.StartTimeHour, rt.StartTimeMinute, rt.StartTimeSecond).TotalSeconds;
                var stop = (int)new TimeSpan(rt.StopTimeHour, rt.StopTimeMinute, rt.StopTimeSecond).TotalSeconds;
                if (rt.IsNextDay)
                {
                    stop += remained; ;
                }

                if (stop < start)
                {
                    Settings.PreStartCountdown = 0;
                    Settings.Duration = -1;
                    return false;
                }

                if (now >= start && now < stop)
                {
                    Settings.PreStartCountdown = 0;
                    Settings.Duration = stop - now;
                    return true;
                }

                if (start < now)
                {
                    start += remained;
                    stop += rt.IsNextDay ? DayToSeconds + remained : remained;
                    now = 0;
                }

                preStartCountdown = start - now;
                if (preStartCountdown < 0)
                {
                    preStartCountdown = start + remained;
                    stop = stop + remained;
                }
                if (preStartCountdown < _preStartCountdown)
                {
                    _preStartCountdown = preStartCountdown;
                    Settings.PreStartCountdown = preStartCountdown;
                    Settings.Duration = stop - start;
                }
            }
            return true;
        }

    }
}
